<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Modules\Blog\Service;


use App\Models\Blog\Search;
use Illuminate\Http\Request;

class SearchService
{

    use Service;

    /**
     * 消息
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function SearchIndexService( $request )
    {
        $user   = $this->getCommon()->UserCommonService();
        $where  = function ( $query ) use ( $request, $user ) {
            $query->where('user_id', $user->id);
            $query->where('status', 1);
            if ( $request->filled('static') ) $query->where('static', $request->input('static'));
            if ( $request->filled('name') ) $query->where('title', $request->input('name'));
            if ( $request->filled('updated_at') ) {
                $time       = $request->input('updated_at');
                $start_time = $time[ 0 ];
                $end_time   = $time[ 1 ];
                $query->whereBetween('updated_at', [ $start_time, $end_time ]);
            }
        };
        $select = [ 'id', 'static', 'title', 'user_id', 'count', 'status', 'updated_at', ];
        $search = Search::GetModel($where, [], $select, $request->input('limit'));
        return data($search);
    }

    /**
     * 修改状态
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function SearchStatusService( $request )
    {
        $user           = $this->getCommon()->UserCommonService();
        $where          = function ( $query ) use ( $request, $user ) {
            $query->where('id', $request->input('id'));
            $query->where('user_id', $user->id);
        };
        $search         = Search::FirstModel($where, [], [ 'id', 'user_id', 'static' ]);
        $search->static = $request->input('static') == 1 ? 1 : 2;
        $search->save();
        return data(NULL, $this->getErrorCode()::message(203));
    }

    /**
     * 删除纪录
     *
     * @param $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function SearchDestroyService( $id )
    {
        $user  = $this->getCommon()->UserCommonService();
        $where = function ( $query ) use ( $id, $user ) {
            if ( ! is_array($id) ) $query->where('id', $id);
            else $query->whereIn('id', $id);
            $query->where('user_id', $user->id);
        };
        Search::DeleteModel($where);
        return data(NULL, $this->getErrorCode()::message(204));
    }

}
